package com.findviewbydream.evil.eda.Answer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.findviewbydream.evil.eda.Activity.BaseActivity;
import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.Data.UserData;
import com.findviewbydream.evil.eda.EventBus.AnswerResultEvent;
import com.findviewbydream.evil.eda.R;
import com.findviewbydream.evil.eda.Utils.Utils;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yuyh.easyadapter.recyclerview.EasyRVAdapter;
import com.yuyh.easyadapter.recyclerview.EasyRVHolder;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.iwgang.familiarrecyclerview.FamiliarRecyclerView;
import okhttp3.Call;


/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda.Answer
 * 时间：16-7-27 上午8:04
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：答题列表界面 继承～/Activity/BaseActivity
 ********************************************/
public class ItemListActivity extends BaseActivity
{
    public static final String FLOW_TYPE = "flowType";
    private static final String TYPE_GETLIST = "getList";

    private SwipeRefreshLayout swipeRefreshLayout;
    private FamiliarRecyclerView recyclerView;
    private CoordinatorLayout coordinatorLayout;
    private SpinKitView loading;

    private Adapter adapter;

    private ArrayList<ItemBean> list;


    @Override
    public int setContentView()
    {
        return R.layout.itemlist;
    }

    @Override
    public String setToolbarTitle()
    {
        return getIntent().getStringExtra("title");
    }

    @Override
    public void onCreate()
    {
        EventBus.getDefault().register(this);

        initView();/*控件初始化*/

        setRecyclerView();/*设置RecyclerView*/

        toNetWork();/*网络加载*/

        setSwipeRefreshLayout();/*设置下拉刷新*/
    }

    /**
     * 控件初始化
     */
    private void initView()
    {
        recyclerView = (FamiliarRecyclerView) findViewById(R.id.recyclerView);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        loading = (SpinKitView) findViewById(R.id.loading);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
    }

    /**
     * 设置下拉刷新
     */
    private void setSwipeRefreshLayout()
    {
        swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light);

        swipeRefreshLayout.setOnRefreshListener(() -> {
            toNetWork();
            recyclerView.setVisibility(View.INVISIBLE);
        });

        /*解决与刷新冲突的问题*/
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
        {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                swipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState)
            {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });


    }

    /**
     * 设置RecyclerView
     */
    private void setRecyclerView()
    {
        list = new ArrayList<>();
        adapter = new Adapter(this, list, R.layout.itemlist_item);
        recyclerView.setAdapter(adapter);

        recyclerView.setOnItemClickListener((familiarRecyclerView, view, position)
                -> startActivity(new Intent(ItemListActivity.this, AnswerActivity.class)
                .putExtra("itemId", list.get(position).itemId)
                .putExtra("position", position)));
    }

    /**
     * 网络加载
     */
    private void toNetWork()
    {
        loading.setVisibility(View.VISIBLE);
        String lastItemId;

        list.clear();/*todo：暂时办法，以后取消(因为当前是直接加载全部的题目，所以也就没有刷新的必要。清空列表，让最后一个值为0，重新加载列表)*/

        if (list != null && list.size() != 0)
            lastItemId = list.get(0).itemId + "";
        else
            lastItemId = "0";

        OkHttpUtils.post().url(Data.IP + "ItemListServlet")
                .addParams("phone", UserData.getUserPhoneNum())
                .addParams("imei", "" + UserData.getUserIMEI())
                .addParams("lastItemId", lastItemId)
                .addParams("type", TYPE_GETLIST)
                .addParams("flowType", getIntent().getStringExtra(FLOW_TYPE))
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        recyclerView.setVisibility(View.VISIBLE);
                        loading.setVisibility(View.GONE);
                        if (swipeRefreshLayout.isRefreshing())
                            swipeRefreshLayout.setRefreshing(false);

                        //NetUtils.reportError(ItemListActivity.this, e);
                        Snackbar.make(ItemListActivity.this.findViewById(R.id.coordinatorLayout)
                                , "啊哦，获取列表失败了……"
                                , Snackbar.LENGTH_LONG)
                                .setAction("重试", view -> toNetWork()).show();
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        recyclerView.setVisibility(View.VISIBLE);
                        loading.setVisibility(View.GONE);
                        if (swipeRefreshLayout.isRefreshing())
                            swipeRefreshLayout.setRefreshing(false);

                        List<ItemListBean> beanList = new Gson().fromJson(response
                                , new TypeToken<List<ItemListBean>>()
                                {
                                }.getType());
                        if (beanList == null || beanList.size() == 0)
                        {
                            findViewById(R.id.null_sign).setVisibility(View.VISIBLE);
                            ImageView img = (ImageView) findViewById(R.id.imageView);
                            Utils.Glide(R.drawable.itemlist_nothing, img);
                        }
                        else
                        {
                            list.clear();
                            for (int i = 0; i < beanList.size(); i++)
                            {
                                ItemListBean bean = beanList.get(i);
                                list.add(new ItemBean(bean.id, bean.imgPath
                                        , bean.title, bean.answer_ids, bean.flow
                                        , bean.createTime, bean.overTime, bean.enabled));
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }
                });

    }

    /*EventBus -> 题目答完，删除该item*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AnswerResultEvent event)
    {
        Utils.Logger(event.position);
        list.remove(event.position);
        adapter.notifyDataSetChanged();
    }


    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 列表适配器
     */
    private class Adapter extends EasyRVAdapter<ItemBean>
    {
        public Adapter(Context context, List<ItemBean> list, int... layoutIds)
        {
            super(context, list, layoutIds);
        }

        @Override
        protected void onBindData(EasyRVHolder viewHolder, int position, ItemBean item)
        {
            ImageView img = viewHolder.getView(R.id.item_img);
            TextView title = viewHolder.getView(R.id.item_title);
            TextView maxDate = viewHolder.getView(R.id.item_maxdate);
            TextView flow = viewHolder.getView(R.id.item_tag);

            Utils.Glide(Utils.getNetImg(item.imgPath), img);
            title.setText(item.title);
            title.setTypeface(Typeface.DEFAULT_BOLD);
            maxDate.setText("限期:" + item.overTime + " 止");
            flow.setText(" " + item.flow + "M");

            if (item.isOverdue)
                viewHolder.getView(R.id.item_isOverdue).setVisibility(View.GONE);
            else
                viewHolder.getView(R.id.item_isOverdue).setVisibility(View.VISIBLE);
        }
    }


    private class ItemBean
    {
        private int itemId;
        private String imgPath;
        private String title;
        private String[] answer_ids;
        private int flow;
        private String createTime;
        private String overTime;
        private boolean isOverdue;

        public ItemBean(int itemId, String imgPath, String title, String[] answer_ids, int flow, String createTime, String overTime, boolean isOverdue)
        {
            this.itemId = itemId;
            this.imgPath = imgPath;
            this.title = title;
            this.answer_ids = answer_ids;
            this.flow = flow;
            this.createTime = createTime;
            this.overTime = overTime;
            this.isOverdue = isOverdue;
        }
    }

    private class ItemListBean
    {
        private int id;
        private String imgPath;
        private String title;
        private String[] answer_ids;
        private int type;
        private int flow;
        private boolean enabled;
        private String createTime;
        private String overTime;
    }


}
   /* todo:   toolbar跟随滑动渐变  备用
    private void setRecyclerViewToolbarAlpha()
    {
        recyclerView.setOnScrollChangeListener(new View.OnScrollChangeListener()
        {
            private float alpha = 1;

            *//*获取滑动距离*//*
            private int getScollYDistance()
            {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int position = layoutManager.findFirstVisibleItemPosition();
                View firstVisiableChildView = layoutManager.findViewByPosition(position);
                int itemHeight = firstVisiableChildView.getHeight();
                return (position) * itemHeight - firstVisiableChildView.getTop();
            }

            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3)
            {
                float heightPixels = ItemListActivity.this.getResources().getDisplayMetrics().heightPixels;
                float scrollY = getScollYDistance();//该值 大于0
                if (alpha >= 0)
                {
                    toolbar.setAlpha(alpha);
                    alpha = 1 - scrollY / (heightPixels / 3);// 0~1  透明度是1~0
                }
                else
                {
                    alpha = 0;
                }
            }
        });

    }*/